package com.abcd.godating.utils.json;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.util.StdDateFormat;

public class CustomDateDeserializer extends JsonDeserializer<Date> {
	public Date deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		JsonToken t = jp.getCurrentToken();
		try {
			if (t == JsonToken.VALUE_NUMBER_INT) {
				return new Date(jp.getLongValue());
			}
			if (t == JsonToken.VALUE_STRING) {
				String str = jp.getText().trim();
				if (str.length() == 0) {
					return null;
				}

				if (str.contains("Date")) {
					str = str.substring(str.indexOf("(") + 1, str.indexOf(")"));
					return new Date(Long.parseLong(str));
				}
				try {
					return StdDateFormat.instance.parse(str);
				} catch (ParseException e) {
					try {
						return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS")
								.parse(str);
					} catch (ParseException e1) {
						try {
							return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
									.parse(str);
						} catch (ParseException localParseException1) {
							return null;
						}
					}
				}
			}
			throw ctxt.mappingException(Date.class);
		} catch (IllegalArgumentException iae) {
			throw ctxt.weirdStringException(Date.class,
					"not a valid representation (error: " + iae.getMessage() + ")");
		}		
	}
}
